<template>
  <div class="card p10 col">
    <label class="title">扫描测试</label>
    <div class="row_center mt">
      <label>列:</label>
      <el-input size="small" v-model="ctx.col" style="width: 60px;"/>
      <label class="ml">行:</label>
      <el-input size="small" v-model="ctx.row" style="width: 60px;"/>
    </div>
    <div class="row_center mt">
      <el-button @click="onClickTestScaner" type="primary">测试扫码枪</el-button>
      <el-button @click="onClickScan" type="primary">{{ ctx.scan_text }}</el-button>
    </div>
  </div>  
</template>

<script setup lang="ts">
import { dialog } from '../../service/ui';
import { scaner_test, cargo_scan, reset_all } from '../../service/main_cmd';
import { reactive } from 'vue';

const TEXT_SCAN = '扫描货道';
const TEXT_STOP = '停止扫描';

interface Ctx {
  col: string,
  row: string,
  scan_text: string,
}

const ctx = reactive<Ctx>({
  col: '0',
  row: '0',
  scan_text: TEXT_SCAN
});

async function onClickTestScaner() {
  try {
    const barcode = await scaner_test();
    dialog.succ(`结果:${barcode}`, 5000);
  } catch (msg) {
    dialog.err(msg);
  }
}

async function scan1_10(col: number) {
  for (let row = 1; row <= 10; row ++) {
    const barcode = await cargo_scan(col, row);
    dialog.succ(`${col}-${row}=>${barcode}`);
    if (ctx.scan_text == TEXT_SCAN) {
      throw '扫描终止';
    }
  }
}

async function scan10_1(col: number) {
  for (let row = 10; row >= 1; row --) {
    const barcode = await cargo_scan(col, row);
    dialog.succ(`${col}-${row}=>${barcode}`);
    if (ctx.scan_text == TEXT_SCAN) {
      throw '扫描终止';
    }
  }
}

async function onClickScanCargo(col: number, row: number) {
  try {
    const barcode = await cargo_scan(col, row);
    dialog.succ(barcode, 5000);
  } catch (msg) {
    dialog.err(msg);
  }
}

async function onClickScan() {
  const col = parseInt(ctx.col);
  const row = parseInt(ctx.row);
  if ((col != 0) && (row != 0)) {
    onClickScanCargo(col, row);
    return;
  }

  if (ctx.scan_text == TEXT_STOP) {
    ctx.scan_text = TEXT_SCAN;
    return;
  }
  ctx.scan_text = TEXT_STOP;
  try {
    await scan1_10(1);
    await scan10_1(2);
    await scan1_10(3);
    await scan10_1(4);
    await scan1_10(5);
    await reset_all();
    dialog.succ('扫描完成');
  } catch (msg) {
    dialog.err(msg);
  }
  ctx.scan_text = TEXT_SCAN;
}



</script>
